# manage the project and project_snapshot model create,update,delete job
class ProjectService
  attr_reader :project,:project_snapshot
  def initialize(project,project_snapshot)
    @project=project
    @project_snapshot=project_snapshot
  end

  def save
    begin
      #params makes the models(database) transaction too
      Project.transaction do
        @project.save!
        @project_snapshot.project=@project
        @project_snapshot.save!
        true
      end
      #exception trigger the transaction block to roll back
    rescue
     false
    end
  end

  def update(project_attr,uploaded_data)
    @project.attributes=project_attr
    #if blank?==true,means not selected the image file
    unless uploaded_data.blank?
     @project_snapshot=ProjectSnapshot.new(:uploaded_data=>uploaded_data)
    end
    begin
      #params makes the models(database) transaction too
      Project.transaction do
        #new_record?=>record not yet saved
       if @project_snapshot.new_record?
          @project.save!
          @project.project_snapshot.destroy
          @project_snapshot.project=@project
          @project_snapshot.save!
          true
        #if new_record?==false,means the image file not selected
       else
         @project.save!
         true
       end
      end
      #exception trigger the transaction block to roll back
    rescue
     false
    end
  end
end

